import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ls_work/a_yyt/widget/yyt_voice_widget.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:ls_work/model/update_file_model.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/native_toast.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';

import '../a_elder/models/upload_entity.dart';
import '../mvp/svp_progress.dart';
import '../net/HttpUtil.dart';
import '../net/api/http_api.dart';
import '../util/toast.dart';

class AddImageWidget extends StatelessWidget {
  List<String> inputFiles = [""];
  List<String> files = [];
  String cameramsg;
  String photomsg;

  Function(List<String> files) onFileSelect;
  int max;

  AddImageWidget(this.onFileSelect,
      {this.max = 9,
      this.files = const [],
      this.cameramsg = '从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限',
      this.photomsg = "从相册选择照片，需要申请您的相册权限"}) {
    inputFiles.insertAll(0, files);
  }

  @override
  Widget build(BuildContext context) {
    return StatefulBuilder(builder: (context, setState) {
      return GridView.count(
        crossAxisCount: 3,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        children: List.generate(min(inputFiles.length, max), (index) {
          var item = inputFiles[index];
          return item.isNullOrEmpty()
              ? Stack(
                  children: [
                    Container(
                      width: double.infinity,
                      height: double.infinity,
                      child: Icon(
                        Icons.add,
                        size: 50,
                        color: Colors.grey,
                      ),
                      margin: EdgeInsets.all(8),
                      decoration: BoxDecoration(
                          color: Color(0xffE9ECEE),
                          borderRadius: 4.borderRadius),
                    ).onTap(() async {
                      showSelectCamera(context, setState);
                    })
                  ],
                )
              : Stack(
                  children: [
                    ImageLoad(
                      item,
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: double.infinity,
                    )
                        .toRound(borderRadius: 4.borderRadius)
                        .addToContainer(margin: EdgeInsets.all(8))
                        .onTap(() {
                      Go().push(ShowImagePage(
                        selectFiles,
                        position: index - 1,
                      ));
                    }),
                    Container(
                      width: 18,
                      height: 18,
                      decoration: BoxDecoration(
                          shape: BoxShape.circle, color: Colors.red),
                      child: Icon(
                        Icons.remove,
                        color: Colors.white,
                        size: 15,
                      ),
                      alignment: Alignment.center,
                    ).onTap(() {
                      setState(() {
                        inputFiles.remove(item);
                        onFileSelect(selectFiles);
                      });
                    }).setLocation(right: 0)
                  ],
                );
        }),
      );
    });
  }

  List<String> get selectFiles {
    var items = <String>[];
    inputFiles.forEach((element) {
      if (element.isNotEmpty) {
        items.insert(0, element);
      }
    });
    return items;
  }

  void showSelectCamera(BuildContext context, StateSetter setState) {
    var items = ['拍摄', '相册'];
    showBottomSelect(context, items: items, onSelect: (str) async {
      if (str == "拍摄") {
        Permission.camera.checkRequestPermission(context, onSuccess: () async {
          var data = await ImagePicker().pickImage(source: ImageSource.camera);

          if (data != null) {
             var compressPath = await NativeUtils.compressImage(data.path);
            setState(() {
              inputFiles.insert(0, compressPath);
            });
          }
          onFileSelect(selectFiles);
        }, msg: "使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限");
      } else if (str == "相册") {

        var isAndroid13 = await isAndroid13OrAbove();
        if(isAndroid13){
          Permission.photos.checkRequestPermission(context, onSuccess: () async {
            var data = await ImagePicker().pickImage(source: ImageSource.gallery);
            if (data != null) {
              var compressPath = await NativeUtils.compressImage(data.path);
              setState(() {
                inputFiles.insert(0, compressPath);
              });
            }
            onFileSelect(selectFiles);
          }, msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限");
        }else{
          Permission.storage.checkRequestPermission(context, onSuccess: () async {
            var data = await ImagePicker().pickImage(source: ImageSource.gallery);
            if (data != null) {
              var compressPath = await NativeUtils.compressImage(data.path);
              setState(() {
                inputFiles.insert(0, compressPath);
              });
            }
            onFileSelect(selectFiles);
          }, msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限");

        }
      }
    });
  }
}

class AddAndUploadImageWidget extends StatelessWidget {
  List<String> inputFiles = [""];
  List<Upload> modelList = [];
  List<String> files = [];
  String cameramsg;
  String photomsg;

  Function(List<String> files, List<Upload> modelList) onFileSelect;
  int max;

  AddAndUploadImageWidget(this.onFileSelect,
      {this.max = 9,
      this.files = const [],
      this.cameramsg = '从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限',
      this.photomsg = "从相册选择照片，需要申请您的相册权限"}) {
    inputFiles.insertAll(0, files);
  }

  @override
  Widget build(BuildContext context) {
    return StatefulBuilder(builder: (context, setState) {
      return GridView.count(
        crossAxisCount: 3,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        children: List.generate(min(inputFiles.length, max), (index) {
          var item = inputFiles[index];
          return item.isNullOrEmpty()
              ? Stack(
                  children: [
                    Container(
                      width: double.infinity,
                      height: double.infinity,
                      child: Icon(
                        Icons.add,
                        size: 50,
                        color: Colors.grey,
                      ),
                      margin: EdgeInsets.all(8),
                      decoration: BoxDecoration(
                          color: Color(0xffE9ECEE),
                          borderRadius: 4.borderRadius),
                    ).onTap(() async {
                      showSelectCamera(context, setState);
                    })
                  ],
                )
              : Stack(
                  children: [
                    ImageLoad(
                      "${HttpApi.imageHead}$item",
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: double.infinity,
                    )
                        .toRound(borderRadius: 4.borderRadius)
                        .addToContainer(margin: EdgeInsets.all(8))
                        .onTap(() {
                      Go().push(ShowImagePage(
                        selectFiles
                            .map((e) => "${HttpApi.imageHead}$e")
                            .toList(),
                        position: index - 1,
                      ));
                    }),
                    Container(
                      width: 18,
                      height: 18,
                      decoration: BoxDecoration(
                          shape: BoxShape.circle, color: Colors.red),
                      child: Icon(
                        Icons.remove,
                        color: Colors.white,
                        size: 15,
                      ),
                      alignment: Alignment.center,
                    ).onTap(() {
                      setState(() {
                        var index = inputFiles.indexOf(item);
                        modelList.remove(index);
                        inputFiles.remove(item);

                        onFileSelect(selectFiles, modelList);
                      });
                    }).setLocation(right: 0)
                  ],
                );
        }),
      );
    });
  }

  List<String> get selectFiles {
    var items = <String>[];
    inputFiles.forEach((element) {
      if (element.isNotEmpty) {
        items.insert(0, element);
      }
    });
    return items;
  }

  void showSelectCamera(BuildContext context, StateSetter setState) {
    var items = ['拍摄', '相册'];
    showBottomSelect(context, items: items, onSelect: (str) async {
      if (str == "拍摄") {
        Permission.camera.checkRequestPermission(context, onSuccess: () async {
          var data = await ImagePicker().pickImage(source: ImageSource.camera);
          if (data != null) {
            upLoadImage(context, data.path, (model) {
              if (data != null) {
                setState(() {
                  inputFiles.insert(0, model.id.toString());
                });
              }
              modelList.insert(0, model);
              onFileSelect(selectFiles, modelList);
            });
          }
        }, msg: "使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限");
      } else if (str == "相册") {
         var isAndroid13 = await isAndroid13OrAbove();
        if(isAndroid13){
          Permission.photos.checkRequestPermission(
            context,
            onSuccess: () async {
              var data =
              await ImagePicker().pickImage(source: ImageSource.gallery);
              if (data != null) {
                upLoadImage(context, data.path, (model) {
                  setState(() {
                    inputFiles.insert(0, model.id.toString());
                  });
                  modelList.insert(0, model);
                  onFileSelect(selectFiles, modelList);
                });
              }
            },
            msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限",
          );
        }else{
          Permission.storage.checkRequestPermission(
            context,
            onSuccess: () async {
              var data =
              await ImagePicker().pickImage(source: ImageSource.gallery);
              if (data != null) {
                upLoadImage(context, data.path, (model) {
                  setState(() {
                    inputFiles.insert(0, model.id.toString());
                  });
                  modelList.insert(0, model);
                  onFileSelect(selectFiles, modelList);
                });
              }
            },
            msg: "从相册选取上传工作照片、长者头像时，需要申请您的相册权限",
          );
        }
      }
    });
  }
}

class UploadVoiceWidget extends StatelessWidget {
  Function(Upload model) onVoiceListener;

  UploadVoiceWidget(this.onVoiceListener);

  @override
  Widget build(BuildContext context) {
    return YYTVoiceWidget(
      startRecord: () {},
      stopRecord: (String? path, num? audioTimeLength) {
        if (!path.isNullOrEmpty()) {
          upLoadImage(context, path!, (model) {
            onVoiceListener(model);
          });
        }
      },
    );
  }
}

///上传
upLoadImage(
    BuildContext context, String path, Function(Upload model) success) async {
  SVProgressHUD page = SVProgressHUD(context);
  page.showProgress();
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  FormData formData = new FormData.fromMap({
    'fileType': path.substring(path.lastIndexOf('.') + 1),
    'fileToUpload': await MultipartFile.fromFile(path, filename: name),
  });
  HttpUtil.instance.getDio().post(HttpApi.upload, data: formData).then((r) {
    ///
    page.closeProgress();
    if (r.statusCode == 200) {
      Map<String, dynamic> map = json.decode(r.toString());

      if (map["code"].toString() == "0") {
        if (map['data'] != null) {
          Upload model = Upload.fromJson(map['data']);
          success(model);
        } else {
          Toast.show(map["msg"]);
        }
      }
    } else {
      Toast.show(r.statusCode.toString());
    }
  }).catchError((e) {
    page.closeProgress();
    print(e.toString());
    Toast.show(getErrorMessage(e));
  });
}
